<?php
class Ab_FrontController{
	private $_controller, $_action, $_params, $_body, $_layout;

	function __construct() {
		$request = $_SERVER['REQUEST_URI'];
		
		$request =substr($request,strlen(SITE_FOLDER));

		$query = explode('?', $request);
		$request=(isset($query[0]) && trim($query[0])!='')? $query[0]:$request;
		$parts = explode('/', trim($request,'/'));
		
		
		//get controller and action	
		//0: index.php|1: file_manager| 2: index
		$this->_controller = !empty($parts[1])?$parts[1]:DEFAULT_CONTROLLER;
		$this->_action = !empty($parts[2])?$parts[2]:DEFAULT_ACTION; 
		
		unset($parts[0]);
		unset($parts[1]);
		unset($parts[2]);
		$parts=array_values($parts);
		
		//get params
		//path:abcd/other_val:cdx/
		if(!empty($parts)){
			for($i=0;$i<count($parts);$i++){
				list($k,$v)=explode(':',$parts[$i]);
				$this->_params[$k] =  $v;
			}
		}		
		
	}

	function dispatch() {		
		 if(class_exists($this->getController())) {
		 	
		    $methods=get_class_methods($this->getController());
		   
		    if(in_array(strtolower($this->getAction()),$methods) || in_array($this->getAction(),$methods)) {
				
			$class = $this->getController();
			$method = $this->getAction();
		    
			$controller_instance = new $class($this);
			$controller_instance->$method();
		    
		    } else {
			throw new NotFoundException();
		    }            
		} else {
			throw new NotFoundException();
		}
	}

	function getParams() {
		return $this->_params;
	}

	function getController() {
		//transform my_controller in Ab_MyControllerController
		return 'Ab_'.str_replace(' ','_',ucwords(str_replace('_',' ',$this->_controller)));
	}

	function getAction() {
		return $this->_action;
	}

	function getBody() {
		return $this->_body;
	}

	function setBody($body) {
		$this->_body = $body;
	}

	function render() {
		return $this->_layout;
	}

	function buildLayout($layer) {
		$this->_layout = $layer;
	}

}

?>
